/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.controller;

import com.bayu.common.lib.CommonUtil;
import com.bayu.services.dao.TStockDao;
import com.bayu.services.entity.TStock;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Bayu
 */
@Controller
@RequestMapping("/tstock-input.htm")
public class TStockInput {
    TStockDao dao;

    @Autowired
    private void setTStockDao(TStockDao tStockDao){
      this.dao = tStockDao;
    }

    @RequestMapping(method = RequestMethod.GET)
    public void displayForm(ModelMap map,String id){
        map.addAttribute("minYear", CommonUtil.getCurrentYear());
        map.addAttribute("maxYear", CommonUtil.getCurrentYear()+3);
    }

    @RequestMapping(method = RequestMethod.POST)
    public String proccessForm(@ModelAttribute("TStock") TStock tStock , BindingResult result,ModelMap map, String idStock,HttpServletRequest req){
            String month = req.getParameter("month");
            String year = req.getParameter("year");

            idStock = month+year;
            String notes = CommonUtil.getMonthName(Integer.parseInt(month)-1)+ " "+ year;




            List total = this.dao.custom("select count(*) from TStock where idStock='"+idStock+"'");

            String strTotal=total.get(0).toString();


            int c = Integer.valueOf(strTotal).intValue();
            System.out.println(strTotal+"---"+c+"--"+idStock);
            if(c > 0){
                return "redirect:ErrorDuplicate.html";
            }else{
                 tStock.setIdStock(idStock);
                 tStock.setNotes(notes);
                 
                 this.dao.save(tStock);
                 return "redirect:view-tstock-data.htm?msg=Data has been updated";

            }
    }
}

